package com.penghe.www.taiwanmap.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Path
import android.os.Handler
import android.os.Message
import android.support.v4.view.GestureDetectorCompat
import android.util.AttributeSet
import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import com.penghe.www.taiwanmap.R
import com.penghe.www.taiwanmap.been.CityItem
import com.penghe.www.taiwanmap.utils.LogUtil
import com.penghe.www.taiwanmap.utils.PathParser
import org.w3c.dom.Document
import org.w3c.dom.Element
import java.io.InputStream
import java.lang.ref.WeakReference
import javax.xml.parsers.DocumentBuilder
import javax.xml.parsers.DocumentBuilderFactory

/**
 * Created by pengh on 2017/6/1.
 *
 * 台湾地图 自定义View
 */

class TaiWanMapView : View {

    /**
     *  companion object 类似于Java的static修饰符
     */
    companion object {
        private val TAG: String = "TaiWanMapView"
    }

    private var selectedCityItem: CityItem? = null
    /**
     * 放大倍数
     */
    private var scaleSize: Float = 1.3f
    private var paint: Paint? = null
    private var viewHandler: ViewHandler? = null
    private var contextWeakreference: WeakReference<Context>? = null
    private val cityItemList: ArrayList<CityItem> = ArrayList()
    private val colorArray: IntArray = intArrayOf(0xFFFF0000.toInt(), 0xFF00FF00.toInt(), 0xFF0000FF.toInt())
    private var gestureDetectorCompat: GestureDetectorCompat? = null

    private val loadMapThread: Thread = object : Thread() {
        override fun run() {
            val context = contextWeakreference!!.get() ?: return

            val inputStream: InputStream = context.resources.openRawResource(R.raw.taiwan_map)
            val documentBuilderFactory: DocumentBuilderFactory = DocumentBuilderFactory.newInstance()
            val documentBuilder: DocumentBuilder = documentBuilderFactory.newDocumentBuilder()
            val document: Document = documentBuilder.parse(inputStream)

            val rootElement: Element = document.documentElement
            val nodeList = rootElement.getElementsByTagName("path")

            for (i in 0..nodeList.length - 1) {
                val element: Element = nodeList.item(i) as Element
                val pathData: String = element.getAttribute("android:pathData")
                LogUtil.w(TAG, "pathData = $pathData")
                //如果panth为空，进入下一个循环
                val path: Path = PathParser.createPathFromPathData(pathData) ?: continue
                val cityItem: CityItem = CityItem(path)
                cityItemList.add(cityItem)
                if (viewHandler != null) {
                    viewHandler!!.sendEmptyMessage(1)
                }
            }
            LogUtil.w(TAG, "size = " + nodeList.length)
        }
    }

    internal class ViewHandler(cityItemList: ArrayList<CityItem>, colorArray: IntArray, mapView: TaiWanMapView) : Handler() {

        private val mCityItemList = cityItemList
        private val mColorArray = colorArray
        private val mMapView = mapView

        override fun handleMessage(msg: Message) {
            when (msg.what) {
                1 -> {
                    val totalNumber: Int = mCityItemList.size
                    for (i in 0..totalNumber - 1) {
                        val color: Int
                        val flag = i % 4
                        when (flag) {
                            0, 1, 2 -> {
                                color = mColorArray[flag]
                            }
                            else -> {
                                color = Color.YELLOW
                            }
                        }
                        mCityItemList[i].setDrawColor(color)
                    }
                    mMapView.postInvalidate()
                }
            }
        }
    }

    constructor(context: Context) : this(context, null)
    constructor(context: Context, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context)
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.save()
        canvas.scale(scaleSize, scaleSize) //放大scaleSize倍
        (0..cityItemList.size - 1)
                .map { cityItemList[it] }
                .filter { it != selectedCityItem }
                .forEach {
                    //如果是未被选中的城市
                    if (paint != null) {
                        it.draw(canvas, paint!!, false)
                    }
                }

        if (selectedCityItem != null) {
            if (paint != null) {
                selectedCityItem!!.draw(canvas, paint!!, true)
            }
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        //将事件转交给gestureDetectorCompat
        return gestureDetectorCompat!!.onTouchEvent(event)
    }


    /**
     * 初始化
     */
    private fun init(context: Context) {
        contextWeakreference = WeakReference(context)
        paint = Paint()
        paint!!.isAntiAlias = true
        loadMapThread.start()
        viewHandler = ViewHandler(cityItemList, colorArray, this)
        gestureDetectorCompat = GestureDetectorCompat(contextWeakreference!!.get(), object : GestureDetector.SimpleOnGestureListener() {
            override fun onDown(e: MotionEvent): Boolean {
                handleTouch(e.x, e.y)
                return true
            }
        })
    }

    /**
     * 处理触摸事件的方法
     *
     * @param x 触摸的屏幕X坐标
     * @param y 触摸的屏幕Y坐标
     */
    private fun handleTouch(x: Float, y: Float) {
        var temp: CityItem? = null
        for (i in cityItemList.indices) {
            val cityItem = cityItemList[i]
            if (cityItem.isTouch((x / scaleSize).toInt(), (y / scaleSize).toInt())) {
                temp = cityItem
                break
            }
        }

        if (temp != null) {
            selectedCityItem = temp
        }

        postInvalidate()
    }

}